from typing import List, Dict
from os import walk
import yaml
from config.settings import CASE_CONFIG_DIR
from common.meta import QuickCaseMeta

# with open('config.yaml', 'r') as f:
#     cfg = yaml.safe_load(f)
#     print(cfg)
# with open('result.yaml', 'w') as f:
#     obj = {'name': 'zss', 'address': ['xian', 'beijing', 'shanghai']}
#     yaml.safe_dump(obj, f)

'''
safe_load:安全的加载方式 推荐使用
yaml.load:非安全加载
返回格式:{'server': {'port': 8080}} 是一个字典
safe_dump:将python对象转为yaml输出到文件中
'''


class YamlScanner:

    @staticmethod
    def scan(path: str) -> List[str]:
        '''
        :param path: scanned dir
        :return: yaml file list
        '''
        yaml_files = []
        paths = walk(path)
        for path, dir_lst, file_lst in paths:  # .\u2 [] ['__init__.py']
            for file in file_lst:
                if file.endswith('.yaml') or file.endswith('.yml'):
                    yaml_files.append('/'.join([path, file]))
        return yaml_files


class QuickTestConvert:
    def convert(self, yaml_file: str):
        yaml_data = {}
        meta_list: List[QuickCaseMeta] = []
        with open(yaml_file, 'r', encoding='utf-8') as f:
            yaml_data: Dict = yaml.safe_load(f)
        case_define_list = yaml_data['cases']
        for case in case_define_list:
            case_meta = self.parse_yaml_config(case)
            meta_list.append(case_meta)

    def parse_yaml_config(self, case_define: dict) -> QuickCaseMeta:
        name = case_define['name']
        uri = case_define['uri']
        method = case_define['method']
        desc = case_define['desc']
        headers = case_define['headers']
        request_type = case_define['request-type']
        is_run = case_define['is-run']
        body = case_define['body']
        _assert = case_define['assert']
        return QuickCaseMeta(
            host='localhost',
            case_name=name,
            uri=uri,
            method=method,
            desc=desc,
            headers=headers,
            request_type=request_type,
            is_run=is_run,
            body=body,
            _assert=_assert
        )


if __name__ == '__main__':
    case_config_files = YamlScanner.scan(CASE_CONFIG_DIR)
    QuickTestConvert().convert(case_config_files[0])
